<template>
  <div style="with:100%;height:100%; position: relative;">
    <div class="homePage">
      <div class="homeTop">
        <wc-swiper>
          <wc-slide v-for="(item, key) in imageLb" :key="key" class="slide">
            <img :src="item.url" alt="" width="100%"
                 height="100%"
            >
          </wc-slide>
        </wc-swiper>
      </div>
      <div class="homeMiddle">
        <el-input
          size="mini"
          placeholder="搜索"
          prefix-icon="el-icon-search"
          style="width:30%"
          class="homeInput"
          @click.native="goSearch"
        />
        <div class="bestBar" @click="goBestBarer">
          今日最杠
          <img src="../../assets/images/podium.png" alt="">
        </div>
      </div>
      <div v-infinite-scroll="load" class="homeBottom infinite-list" infinite-scroll-delay="800"
           :infinite-scroll-disabled="scrollFlag"
      >
        <div v-for="(item,index) in subjectInfo" :key="index" class="contentItem"
             @click="goInfo(item)"
        >
          <div class="itemTop">
            <div class="userInfo">
              <div class="userPicture">
                <img :src="baseUrl+item.userImg" alt="" width="36px"
                     height="36px"
                >
              </div>
              <p>
                {{ item.userName }}  <span class="date">{{ getTimeToDate(item.posttime) }}前</span><br>
                <el-tag :type="item.userExperType" size="mini">
                  Lv.{{ item.userexper }} {{ item.userExperDes }}
                </el-tag>
              </p>
            </div>
            <i class="el-icon-more-outline" style="margin-top:-20px" />
          </div>
          <div class="itemContent">
            {{ item.qtitle }}
            <p>{{ item.qdesc }}</p>
            <div class="options">
              <div v-if="!item.showFlag">
                <el-button
                  plain
                  round
                  type="primary"
                  @click.stop="doOption(item,'one')"
                >
                  {{ item.optionOne }}
                </el-button>
                <el-button
                  plain
                  round
                  type="danger"
                  @click.stop="doOption(item,'two')"
                >
                  {{ item.optionTwo }}
                </el-button>
              </div>
              <div v-else class="showOption">
                <div :class="item.bgOption">
                  {{ item.bgOption==='bgOptionOne'?item.optionOne:item.optionTwo }}
                </div>
                <div class="progressText">
                  <div class="progressTop">
                    <p>{{ item.optionOne }}{{ item.optionsNum1 }}</p>
                    <p>{{ item.optionTwo }}{{ item.optionsNum2 }}</p>
                  </div>
                  <el-progress
                    :percentage="item.percent"
                    :format="format"
                    :text-inside="true"
                    :stroke-width="6"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="itemFooter">
            <div><svg-icon icon-class="fire" /> {{ item.discussNum }}</div>
            <div class="tagNum">
              <i class="el-icon-chat-line-square"> {{ item.remarknum }}</i>
              <i v-if="!item.showStarFlag" class="el-icon-star-off" @click.stop="starLike(item)"> {{ item.starnum }}</i>
              <i v-else class="el-icon-star-on" style="color:#F56C6C;"> {{ item.starnum }}</i>
            </div>
          </div>
        </div>
        <div class="blank" style="width:100%;height:30px" />
      </div>
    </div>
    <div class="writeTitle" @click="goSubjectWrite">
      <i class="el-icon-edit-outline" />
      <div class="textTit">
        | 输入你想杠的题目...
      </div>
      <el-button type="primary" round size="mini">
        写杠题
      </el-button>
    </div>
    <div v-if="showModal" class="loadingModel">
      <div class="content">
        <i class="el-icon-loading" /><br>
        加载中
      </div>
    </div>
    <el-backtop target=".homePage" :bottom="100" :right="20">
      <i class="el-icon-caret-top" />
    </el-backtop>
  </div>
</template>
<script>
import { getSubjectInfo, getOptionsByUid, getOptionsByQid, chooseOption, getStar, getStarByUid, addStarByUser } from '../../api/subject';
import { getTimeToDate, transformTimestamp } from '../../utils/validate';
export default {
  data() {
    return {
      imageLb: [
        { url: require('../../assets/images/lbt1.jpg') },
        { url: require('../../assets/images/lbt2.jpg') },
        { url: require('../../assets/images/lbt3.jpg') },
        { url: require('../../assets/images/lbt4.jpg') }
      ],
      subjectParam: {
        start: 0,
        num: 5
      },
      subjectInfo: [],
      userExperType: 'info',
      userExperDes: '杠铃',
      scrollFlag: false,
      showModal: false,
      baseUrl: '',
      userOption: [],
      userStars: []
    };
  },
  created() {
    this.getSubjectMessage();
    this.baseUrl = process.env.VUE_APP_DEV_TARGET;
  },
  methods: {
    getTimeToDate,
    renderUserTag(obj) {
      const qidArray = [];
      const qidArrayByStar = [];
      this.userOption.forEach(item => {
        qidArray.push(item.qid);
      });
      this.userStars.forEach(item => {
        qidArrayByStar.push(item.qid);
      });
      obj.forEach(item => {
        this.$set(item, 'showFlag', false);
        this.$set(item, 'showStarFlag', false);
        this.$set(item, 'bgOption', '');
        if (qidArray.includes(item.qid)) {
          this.userOption.forEach(elem => {
            if (item.qid === elem.qid) {
              if (elem.useroption === 1) {
                this.$set(item, 'bgOption', 'bgOptionOne');
              } else {
                this.$set(item, 'bgOption', 'bgOptionTwo');
              }
            }
          });
          this.$set(item, 'showFlag', true);
        }
        if (qidArrayByStar.includes(item.qid)) {
          this.$set(item, 'showStarFlag', true);
        }
        switch (item.userexper) {
        case 1:
          this.$set(item, 'userExperType', 'info');
          this.$set(item, 'userExperDes', '杠师');
          break;
        case 2:
          this.$set(item, 'userExperType', 'success');
          this.$set(item, 'userExperDes', '杠尊');
          break;
        case 3:
          this.$set(item, 'userExperType', '');
          this.$set(item, 'userExperDes', '杠王');
          break;
        case 4:
          this.$set(item, 'userExperType', 'warning');
          this.$set(item, 'userExperDes', '杠圣');
          break;
        case 5:
          this.$set(item, 'userExperType', 'danger');
          this.$set(item, 'userExperDes', '杠神');
          break;
        default:
          break;
        }
      });
    },
    goToInfo() {
      this.$router.push({ name: 'subjectinfo' });
    },
    // 去搜索
    goSearch() {
      this.$router.push({ name: 'subjectSearch' });
    },
    // 去今日最杠
    goBestBarer() {
      this.$router.push({ name: 'bestBarer' });
    },
    // 去新建杠题
    goSubjectWrite() {
      this.$router.push({ name: 'subjectWrite' });
    },
    // 得到杠题
    async  getSubjectMessage() {
      this.showModal = true;
      await this.getOptionsByUser();
      await this.getStarByUser();
      await getSubjectInfo(this.subjectParam).then(res => {
        if (res.data.code === 200) {
          this.scrollFlag = false;
          this.renderUserTag(res.data.data);
          this.getOptionsBySubject(res.data.data);
          if (res.data.data.length === 0) {
            this.scrollFlag = true;
          }
          this.showModal = false;
        }
      });
    },
    // 滚动
    load() {
      this.subjectParam.start += 5;
      this.getSubjectMessage();
    },
    doOption(item, option) {
      let optionFlag = 0;
      if (option === 'one') {
        optionFlag = 1;
        this.$set(item, 'optionsNum1', ++item.optionsNum1);
        this.$set(item, 'bgOption', 'bgOptionOne');
      } else {
        optionFlag = 2;
        this.$set(item, 'optionsNum2', ++item.optionsNum2);
        this.$set(item, 'bgOption', 'bgOptionTwo');
      }
      this.$set(item, 'percent', parseInt(item.optionsNum1 / (item.optionsNum1 + item.optionsNum2) * 100));
      this.$set(item, 'discussNum', ++item.discussNum);
      const params = {
        qid: item.qid,
        uid: this.$store.getters.userInfo.uid,
        useroption: optionFlag,
        optionDate: transformTimestamp(new Date())
      };
      chooseOption(params).then(res => {
        if (res.data.code === 200) {
          this.$set(item, 'showFlag', true);
        }
      });
    },
    // 得到用户的选择表
    getOptionsByUser() {
      const param = { uid: this.$store.getters.userInfo.uid };
      getOptionsByUid(param).then((res) => {
        if (res.data.code === 200) {
          this.userOption = res.data.data;
        }
      });
    },
    // 得到题目的选择表
    getOptionsBySubject(objItem) {
      getOptionsByQid().then((res) => {
        if (res.data.code === 200) {
          const resultMap = res.data.data.reduce((pre, next) => {
            if (next.qid in pre) {
              pre[next.qid] = pre[next.qid].concat([next]);
            } else {
              pre[next.qid] = [next];
            }
            return pre;
          }, {});
          for (const key in resultMap) {
            let optionsNum1 = 0;
            let optionsNum2 = 0;
            if (Object.hasOwnProperty.call(resultMap, key)) {
              resultMap[key].forEach(item => {
                if (item.useroption === 1) {
                  optionsNum1++;
                } else {
                  optionsNum2++;
                }
              });
              resultMap[key] = {
                'optionsNum1': optionsNum1,
                'optionsNum2': optionsNum2,
                'percent': parseInt(optionsNum1 / (optionsNum1 + optionsNum2) * 100)
              };
            }
          }
          objItem.forEach(item => {
            if (item.qid in resultMap) {
              this.$set(item, 'optionsNum1', resultMap[item.qid].optionsNum1);
              this.$set(item, 'optionsNum2', resultMap[item.qid].optionsNum2);
              this.$set(item, 'percent', resultMap[item.qid].percent);
            }
          });
          this.subjectInfo = this.subjectInfo.concat(objItem);
        }
      });
    },
    // 得到用户的收藏表
    getStarByUser() {
      const param = { uid: this.$store.getters.userInfo.uid };
      getStarByUid(param).then((res) => {
        if (res.data.code === 200) {
          this.userStars = res.data.data;
        }
      });
    },
    // 得到所有收藏表
    getAllStar() {
      getStar().then(res => {
        if (res.data.code === 200) {
          const resultMap = res.data.data.reduce((pre, next) => {
            if (next.qid in pre) {
              pre[next.qid] = pre[next.qid].concat([next]);
            } else {
              pre[next.qid] = [next];
            }
            return pre;
          }, {});
          console.log(resultMap);
        }
      });
    },
    format() {
      return '';
    },
    // 点击收藏
    starLike(item) {
      const params = {
        uid: this.$store.getters.userInfo.uid,
        qid: item.qid,
        sDate: transformTimestamp(new Date())
      };
      addStarByUser(params).then(res => {
        if (res.data.code === 200) {
          this.$set(item, 'starnum', ++item.starnum);
          this.$set(item, 'showStarFlag', true);
        }
      });
    },
    // 题目详情
    goInfo(item) {
      //  this.$router.push({ name: 'personalMessage', params: { id: item } });
      this.$router.push({ name: 'subjectinfo', params: { subjectItem: item } });
    }
  }
};
</script>
<style>
.homeInput .el-input__inner{
  border-radius: 20px;
  border: none;
  background: #EBEEF5;
}
.el-progress-bar__outer{
  background: #F56C6C;
}
</style>
<style lang="scss" scoped>
.homePage{
  height: 100%;
  width: 100%;
  background-color: #F2F6FC;
  overflow-y: auto;
  overflow-x: hidden;
  .homeTop{
    width: 100%;
    height: 35%;
    position: relative;
    .wc-swiper-container{
      width: 100%;
      height: 100%;
    }
  }
  .homeMiddle{
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    display: flex;
    padding:0px 10px ;
    box-sizing: border-box;
    background-color: #fff;
    align-items: center;
    justify-content: space-between;
    box-shadow: 1px 5px 5px #d7dae0;
    .bestBar{
      font-size: 14px;
      color: #5e5e5e;
      display: flex;
      justify-content: center;
      align-items: center;
      img{
        width: 36px;
        height: 36px;
      }
    }
  }
  .homeBottom{
    width: 100%;
    height: 1000px;
    .contentItem{
      box-sizing: border-box;
      width: 100%;
      height: auto;
      background: #fff;
      box-shadow: 1px 2px 2px #d7dae0;
      margin-bottom: 10px;
      padding: 10px;
      .itemTop{
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        .userInfo{
          display: flex;
          .userPicture{
            width: 36px;
            height: 36px;
            overflow: hidden;
            border-radius: 100%;
            margin-right: 10px;
          }
          p{
            font-size: 16px;
            color: #3d3d3d;
            font-weight: bold;
            .date{
              font-size:10px;
              font-weight:normal;
              color: #909399;
              display: inline-block;
              margin-left: 5px;
            }
            .el-tag{
              font-size: 10px  !important;
            }
          }
        }
      }
      .itemContent{
         width: 100%;
         font-size: 16px;
         font-weight: bold;
         margin-top: 15px;
         p{
           margin-top: 5px;
           font-size: 14px;
           line-height: 28px;
           color: #4b4b4b;
         }
         .options{
           margin-top: 10px;
           .el-button{
             width: 120px;
             padding: 8px;
             background-color: transparent;
           }
           .showOption{
             width: 100%;
             display: flex;
             align-items: center;
             .bgOptionOne{
               text-align: center;
               width: 20%;
               padding: 8px;
               font-size: 14px;
               border-radius: 20px;
               color: #fff;
               background: #409EFF;
             }
             .bgOptionTwo{
               text-align: center;
               width: 20%;
               padding: 8px;
               font-size: 14px;
               border-radius: 20px;
               color: #fff;
               background: #F56C6C;
             }
             .progressText{
               margin: 0 auto;
               margin-top: -15px;
               width: 70%;
               .progressTop{
                 display: flex;
                 justify-content: space-between;
                 align-items: center;
                 margin-bottom: -10px;
                p{
                  font-size: 12px;
                  font-weight: bold;
                  color: #409EFF;
                }
                p:last-child{
                  color: #F56C6C;
                }
               }
             }
           }
         }
      }
      .itemFooter{
         width: 100%;
         margin-top: 10px;
         display: flex;
         justify-content: space-between;
         align-items: center;
         font-size: 14px;
         color: #5e5e5e;
         .svg-icon{
           width: 16px;
           height: 16px;
         }
         .tagNum{
           font-size: 16px;
           i{
             margin-right: 10px;
           }
         }
      }
    }
  }
}
.writeTitle{
    position: absolute;
    bottom: 0px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    z-index: 999;
    width: 100%;
    height: 36px;
    color: #909399;
    font-size: 14px;
    background-color:#EBEEF5;
    box-shadow: 5px 0px 5px rgb(202, 201, 201);
    i{
      font-size: 20px;
      color: #409EFF;
    }
    .textTit{
      width: 70%;
    }
}
.loadingModel{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background: rgba($color: #000000, $alpha: 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
   color: #F2F6FC;
  .content{
    text-align: center;
    font-size: 16px;
     i{
       font-size: 30px;
       margin-bottom: 10px;
      }
  }
}
</style>
